﻿Public Class FMain
    Private Class ImageKeys
        Public Const BuddyOnline As String = "bu"
        Public Const BuddyOffline As String = "bo"
    End Class

    Private Sub FMain_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        BrowseBuddies1.Stop()
        FileShare.Manager.Stop()
        NetNode.Manager.Stop()
        SetupEvents(False)
        Utils.Threading.MainGuiForm = Nothing
    End Sub

    Private Sub SetupEvents(ByVal startListening As Boolean)
        If startListening Then
            AddHandler NetNode.Manager.ClientStatusChanged, AddressOf EventHandler_ClientStatusChanged
            AddHandler NetNode.Manager.ClientException, AddressOf EventHandler_ClientException
            AddHandler NetNode.Manager.ClientLogEvent, AddressOf EventHandler_ClientLogEvent
            AddHandler DataStore.Buddies.BuddyCreated, AddressOf EventHandler_BuddyCreated
            AddHandler DataStore.Buddies.BuddyUpdated, AddressOf EventHandler_BuddyUpdated
            AddHandler DataStore.Buddies.BuddyDeleted, AddressOf EventHandler_BuddyDeleted
            AddHandler FileShare.Manager.LogEvent, AddressOf EventHandler_FileShareLogEvent
            AddHandler FileShare.Manager.ShareDeleted, AddressOf EventHandler_ShareDeleted
        Else
            RemoveHandler NetNode.Manager.ClientStatusChanged, AddressOf EventHandler_ClientStatusChanged
            RemoveHandler NetNode.Manager.ClientException, AddressOf EventHandler_ClientException
            RemoveHandler NetNode.Manager.ClientLogEvent, AddressOf EventHandler_ClientLogEvent
            RemoveHandler DataStore.Buddies.BuddyCreated, AddressOf EventHandler_BuddyCreated
            RemoveHandler DataStore.Buddies.BuddyUpdated, AddressOf EventHandler_BuddyUpdated
            RemoveHandler DataStore.Buddies.BuddyDeleted, AddressOf EventHandler_BuddyDeleted
            RemoveHandler FileShare.Manager.LogEvent, AddressOf EventHandler_FileShareLogEvent
            RemoveHandler FileShare.Manager.ShareDeleted, AddressOf EventHandler_ShareDeleted
        End If
    End Sub

    Private Sub NetworkSettingsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NetworkSettingsToolStripMenuItem.Click
        SetupNetNode.Manager.SetupNetNode(Me)
    End Sub

    Private Sub FMain_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Text = String.Format("{0} - {1}:{2} - B2B", NetNode.Settings.Nickname, NetNode.Settings.Host, NetNode.Settings.Port)
        Me.Icon = CommonResources.My.Resources.Buddy

        ImageList1.Images.Add(ImageKeys.BuddyOnline, CommonResources.My.Resources.Buddy_Online)
        ImageList1.Images.Add(ImageKeys.BuddyOffline, CommonResources.My.Resources.Buddy_Offline)

        lvwBuddies.BeginUpdate()
        For Each clsBuddy As Entities.Buddy In DataStore.Buddies.GetAll
            UpdateBuddyItem(clsBuddy)
        Next
        lvwBuddies.EndUpdate()

        lvwSharedFolders.BeginUpdate()
        For Each clsShare As Entities.SharedWatchFolder In DataStore.SharedWatchFolders.GetAll
            UpdateSharedFolder(clsShare, True)
        Next
        lvwSharedFolders.EndUpdate()

        BrowseBuddies1.Init()

        SetupEvents(True)
    End Sub

    Private Sub EventHandler_BuddyUpdated(ByVal buddy As Entities.Buddy)
        Try
            For Each clsItem As ListViewItem In lvwBuddies.Items
                Dim clsBud As Entities.Buddy = CType(clsItem.Tag, Entities.Buddy)
                If clsBud.Id = buddy.Id Then
                    UpdateBuddyItem(clsItem, buddy)
                    Exit For
                End If
            Next
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_BuddyDeleted(ByVal buddy As Entities.Buddy)
        Try
            For Each clsItem As ListViewItem In lvwBuddies.Items
                Dim clsBud As Entities.Buddy = CType(clsItem.Tag, Entities.Buddy)
                If clsBud.Id = buddy.Id Then
                    clsItem.Remove()
                    Exit For
                End If
            Next
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_BuddyCreated(ByVal buddy As Entities.Buddy)
        Try
            UpdateBuddyItem(lvwBuddies.Items.Add(String.Empty), buddy)
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub

    Private Sub UpdateSharedFolder(ByVal share As Entities.SharedWatchFolder, ByVal fromLoad As Boolean)
        If share Is Nothing Then Return
        Dim clsItem As ListViewItem = Nothing
        If fromLoad Then
            For Each clsTmpItem As ListViewItem In lvwSharedFolders.Items
                Dim clsShare As Entities.SharedWatchFolder = CType(clsTmpItem.Tag, Entities.SharedWatchFolder)
                If share.Id = clsShare.Id Then
                    clsItem = clsTmpItem
                    Exit For
                End If
            Next
        End If
        If clsItem Is Nothing Then
            clsItem = lvwSharedFolders.Items.Add(String.Empty)
            While clsItem.SubItems.Count < 5
                clsItem.SubItems.Add(String.Empty)
            End While
        End If
        clsItem.Text = share.Name
        clsItem.SubItems(1).Text = share.GroupMode.ToString
        clsItem.SubItems(2).Text = share.ItemTypes.ToString
        clsItem.SubItems(3).Text = CStr(IIf(share.Recursive, "Yes", "No"))
        clsItem.SubItems(4).Text = share.Path
        clsItem.Tag = share
    End Sub


    Private Sub UpdateBuddyItem(ByVal buddy As Entities.Buddy)
        If buddy Is Nothing Then Return
        For Each clsItem As ListViewItem In lvwBuddies.Items
            Dim clsBud As Entities.Buddy = CType(clsItem.Tag, Entities.Buddy)
            If buddy.Id = clsBud.Id Then
                UpdateBuddyItem(clsItem, clsBud)
                Return
            End If
        Next
        UpdateBuddyItem(lvwBuddies.Items.Add(String.Empty), buddy)
    End Sub
    Private Sub UpdateBuddyItem(ByVal item As ListViewItem, ByVal buddy As Entities.Buddy)
        While item.SubItems.Count < 3
            item.SubItems.Add(String.Empty)
        End While
        item.Text = buddy.Name
        item.SubItems(1).Text = NetNode.Manager.GetBuddyStatusText(buddy)
        item.SubItems(2).Text = buddy.Comment
        If NetNode.Manager.IsBuddyOnline(buddy) Then
            item.ImageKey = ImageKeys.BuddyOnline
        Else
            item.ImageKey = ImageKeys.BuddyOffline
        End If
        item.Tag = buddy
    End Sub

    Private Sub EventHandler_ClientStatusChanged(ByVal client As NetNode.Client)
        Try
            lvwLog.Items.Add(String.Format("Status changed {0}: {1}", client.NetworkId, NetNode.Manager.GetBuddyStatusText(client.Buddy)))
            lvwLog.EnsureVisible(lvwLog.Items.Count - 1)
            UpdateBuddyItem(client.Buddy)
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_ClientDisonnected(ByVal client As NetNode.Client)
        Try
            lvwLog.Items.Add("Disconnected: " & client.NetworkId)
            lvwLog.EnsureVisible(lvwLog.Items.Count - 1)
            UpdateBuddyItem(client.Buddy)
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_ClientException(ByVal client As NetNode.Client, ByVal exception As Exception)
        Try
            With lvwLog.Items.Add("Exception: " & client.NetworkId & " " & exception.Message)
                .Tag = exception
            End With
            lvwLog.EnsureVisible(lvwLog.Items.Count - 1)
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_ClientLogEvent(ByVal client As NetNode.Client, ByVal info As String)
        Try
            lvwLog.Items.Add("Log: " & client.NetworkId & " " & info)
            lvwLog.EnsureVisible(lvwLog.Items.Count - 1)
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub
    Private Sub EventHandler_FileShareLogEvent(ByVal text As String, ByVal tag As Object)
        Try
            With lvwLog.Items.Add("Log: " & text)
                .Tag = tag
            End With
            lvwLog.EnsureVisible(lvwLog.Items.Count - 1)
        Catch ex As Exception
            Utils.Misc.HandleException(Me, ex)
        End Try
    End Sub


    Private Sub IssueConnectPinCodeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IssueConnectPinCodeToolStripMenuItem.Click
        If NetNode.Settings.Listen Then
            Dim clsView As New FIssueNewPairUpTicket
            clsView.Show(Me)
        Else
            MessageBox.Show(Me, "You can only issue pair up tickets if your node is setup to be public and listen to incoming connections!", "Pair Up Ticket", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
        End If
    End Sub

    Private Sub ViewActiveTicketsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewActiveTicketsToolStripMenuItem.Click
        Dim clsView As New FViewActivePairUpTickets
        clsView.Show(Me)
    End Sub

    Private Sub EnterPairUpTicketToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnterPairUpTicketToolStripMenuItem.Click
        Dim clsView As New FEnterPairUpTicket
        clsView.Show(Me)
    End Sub

    Private Sub lvwLog_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvwLog.MouseDoubleClick
        If lvwLog.SelectedItems.Count = 1 Then
            Dim clsTag As Object = lvwLog.SelectedItems(0).Tag
            If TypeOf clsTag Is Exception Then
                Dim ex As Exception = CType(clsTag, Exception)
                Dim sText As String = String.Format("{0}{1}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace)
                MessageBox.Show(Me, sText, "Exception details", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End If
    End Sub

    Private Sub DeleteBuddyToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DeleteBuddyToolStripMenuItem.Click
        Dim sText As String = Nothing
        Dim aBuds As New Generic.List(Of Entities.Buddy)
        Select Case lvwBuddies.SelectedItems.Count
            Case 0
                Return
            Case 1
                Dim clsBud As Entities.Buddy = CType(lvwBuddies.SelectedItems(0).Tag, Entities.Buddy)
                aBuds.Add(clsBud)
                sText = String.Format("Are you sure you want to delete the buddy {0}?", clsBud.Name)
            Case Is > 1
                Dim clsSB As New System.Text.StringBuilder
                For i As Integer = 0 To lvwBuddies.SelectedItems.Count - 1
                    Dim clsBud As Entities.Buddy = CType(lvwBuddies.SelectedItems(i).Tag, Entities.Buddy)
                    If i = lvwBuddies.SelectedItems.Count - 1 Then
                        clsSB.Append(", and ")
                    ElseIf i > 0 Then
                        clsSB.Append(", ")
                    End If
                    clsSB.Append(clsBud.Name)
                    aBuds.Add(clsBud)
                Next
                sText = String.Format("Are you sure you want to delete the {0} selected buddies {1}?", lvwBuddies.SelectedItems.Count, clsSB.ToString)
        End Select

        Select Case MessageBox.Show(Me, sText, "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
            Case Windows.Forms.DialogResult.Yes
            Case Else
                Return
        End Select

        For Each clsBud As Entities.Buddy In aBuds
            DataStore.Buddies.Delete(clsBud)
        Next
    End Sub

    Private Sub ConnectBuddy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConnectBuddy.Click
        For Each clsItem As ListViewItem In lvwBuddies.SelectedItems
            Dim clsBud As Entities.Buddy = CType(clsItem.Tag, Entities.Buddy)
            NetNode.Manager.StartConnect(clsBud, False)
        Next
    End Sub

    Private Sub DisconnectBuddy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DisconnectBuddy.Click
        For Each clsItem As ListViewItem In lvwBuddies.SelectedItems
            Dim clsBud As Entities.Buddy = CType(clsItem.Tag, Entities.Buddy)
            NetNode.Manager.Disconnect(clsBud)
        Next
    End Sub

    Private Sub ViewSharedItemsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ViewSharedItemsToolStripMenuItem.Click
        ShowSharedItemsForSelectedShare()
    End Sub

    Private Sub lvwSharedFolders_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles lvwSharedFolders.MouseDoubleClick
        ShowSharedItemsForSelectedShare()
    End Sub

    Private Sub ShowSharedItemsForSelectedShare()
        If lvwSharedFolders.SelectedItems.Count <> 1 Then Beep() : Return
        Dim clsShare As Entities.SharedWatchFolder = CType(lvwSharedFolders.SelectedItems(0).Tag, Entities.SharedWatchFolder)
        FileShare.FViewSharedItems.Show(Me, clsShare)
    End Sub

    Private Sub RescanForChangesMenuToolItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RescanForChangesMenuToolItem.Click
        If lvwSharedFolders.SelectedItems.Count <> 1 Then Beep() : Return
        Dim clsShare As Entities.SharedWatchFolder = CType(lvwSharedFolders.SelectedItems(0).Tag, Entities.SharedWatchFolder)
        FileShare.Manager.RescanShare(clsShare)
    End Sub

    Private Sub GenerateOpenMediaInfoToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles GenerateOpenMediaInfoToolStripMenuItem.Click
        OpenMediaInfo.FGenerateOpenMediaInfo.ShowIt()
    End Sub

    Private Sub RemoveShareToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemoveShareToolStripMenuItem.Click
        If lvwSharedFolders.SelectedItems.Count = 1 Then
            Dim clsShare As Entities.SharedWatchFolder = CType(lvwSharedFolders.SelectedItems(0).Tag, Entities.SharedWatchFolder)
            Select Case MessageBox.Show(Me, String.Format("Delete {0}?", clsShare.Name), "Delete Share", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2)
                Case Windows.Forms.DialogResult.Yes
                Case Else
                    Return
            End Select
            FileShare.Manager.DeleteShare(clsShare)
        End If
    End Sub

    Private Sub EventHandler_ShareDeleted(ByVal share As Entities.SharedWatchFolder)
        For Each clsItem As ListViewItem In lvwSharedFolders.Items
            If CType(clsItem.Tag, Entities.SharedWatchFolder).Id = share.Id Then
                clsItem.Remove()
                Exit For
            End If
        Next
    End Sub
End Class
